const ts = require('ohos-typescript');
const fs = require('fs');

class ImportsCounter {
    constructor() {
        this.moduleMap = new Map();
    }

    countImports(path) {
        const stats = fs.statSync(path);
        if (stats.isFile()) {
            this.countImportsInAFile(path)
        } else if (stats.isDirectory()) {
            fs.readdirSync(path).forEach(file=>this.countImports(path + '/' + file))
        }
    }

    countImportsInAFile(filePath) {
        if (!filePath.endsWith('.ts') && !filePath.endsWith('.ets')) {
            return
        }
        const sourceFile = ts.createSourceFile(filePath,
            fs.readFileSync(filePath, 'utf-8'),
            ts.ScriptTarget.ESNext,
            true
        );

        const visitNode = (node) => {
            if (ts.isImportDeclaration(node)) {
                const moduleName = node.moduleSpecifier.getText();
                if (!this.moduleMap.has(moduleName)) {
                    this.moduleMap.set(moduleName, new Set());
                }

                const importClauseText = node.importClause.getText();
                const regex = /(\w+),/g;
                const matches = importClauseText.match(regex);
                if (matches === null) {
                    this.moduleMap.get(moduleName).add(this.formatClauseText(importClauseText));
                } else {
                    matches.forEach((match) => {
                        this.moduleMap.get(moduleName).add(this.formatClauseText(match));
                    });
                }
            }
            ts.forEachChild(node, visitNode);
        };
        ts.forEachChild(sourceFile, visitNode);
    }

    formatClauseText(text) {
        if (text.startsWith('*')) {
            return '*'
        }
        return text.replace(/[\{\},\s]/g, '').trim()
    }

    writeResult(write) {
        write("imported modules:");
        this.moduleMap.forEach((value, key) => {
            value.forEach((v) => {
                write(`Module: ${key}, Component: ${v}`);
            })
        })
    }
}

const args = process.argv.slice(2);
const options = {};

args.forEach(arg => {
    if (arg.startsWith('--')) {
        const [key, value] = arg.slice(2).split('=');
        options[key] = value || true;
    }
});

const counter = new ImportsCounter();
if (options['src']) {
    counter.countImports(options['src']);
} else {
    console.log('Should input src path!')
    process.exit();
}

if (options['output']) {
    const writer = fs.createWriterStream(options['output'], { encoding: 'utf-8', options: 'r+'})
    counter.writeResult((content) => writer.write(`${content}\n`));
} else {
    counter.writeResult((content) => console.log(content));
}
